package com.fundcrawler.web;

import com.fundcrawler.common.Constants;
import com.fundcrawler.dto.FundValuationDTO;
import com.fundcrawler.dto.Response;
import com.fundcrawler.entity.FundNav;
import com.fundcrawler.service.DataService;
import com.fundcrawler.service.FundCrawlerAspxService;
import com.fundcrawler.service.manager.FundNavManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/api")
public class FundController {

    @Autowired
    private FundNavManager fundNavManager;
    @Autowired
    private DataService dataService;
    @Autowired
    private FundCrawlerAspxService fundCrawlerAspxService;

    @GetMapping("/fund/nav-trend")
    public Map<String, Object> getNavTrend(@RequestParam String fundCode) {
        List<FundNav> data = dataService.getRecentNavs(fundCode, 90);
        List<String> dates = new ArrayList<>();
        List<Double> unitNavs = new ArrayList<>();
        for (FundNav nav : data) {
            dates.add(nav.getDate().format(DateTimeFormatter.ISO_LOCAL_DATE));
            unitNavs.add(nav.getUnitNav().doubleValue());
        }
        Map<String, Object> result = new HashMap<>();
        result.put("dates", dates);
        result.put("unitNav", unitNavs);
        return result;
    }

    @GetMapping("/export/excel")
    public void exportToExcel(HttpServletResponse response) throws IOException {
        List<FundNav> data = dataService.getAllData();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=fund_data_" + 
            System.currentTimeMillis() + ".xlsx");
        // 需引入 EasyExcel 写出
    }

    @GetMapping("/export/csv")
    public void exportToCsv(HttpServletResponse response) throws IOException {
        List<FundNav> data = dataService.getAllData();
        response.setContentType("text/csv;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=fund_data_" + 
            System.currentTimeMillis() + ".csv");
        PrintWriter writer = response.getWriter();
        writer.write("\uFEFF");
        // 这里应写入 CSV 内容
    }

    @GetMapping("/fund/crawl/{code}")
    public Response crawl(@PathVariable String code) {
        try {
            if(Constants.FETCH_ALL_CODE.equals(code)){
                dataService.updateAllFunds();
            }else{
                fundCrawlerAspxService.crawlFundHistory(code);
            }
            return Response.message("基金 " + code + " 数据爬取完成");
        } catch (Exception e) {
            return Response.error("失败: " + e.getMessage());
        }
    }

    // ✅ RESTful 接口：返回 JSON 数据
    @GetMapping("/fund/valuation")
    public List<FundValuationDTO> getValuationStats(
            @RequestParam String fundCode,
            @RequestParam Double unitNav) {
        return fundNavManager.getValuationStats(fundCode, unitNav);
    }

    // ✅ 分页查询基金净值
    @GetMapping("/fund/navs")
    public Page<FundNav> getNavs(
            @RequestParam String fundCode,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        return fundNavManager.findByFundCode(fundCode, PageRequest.of(page, size));
    }
}
